import mongoose from "mongoose"
import util from "@mazp/util"

const skillSchema = new mongoose.Schema({
  percent: {
    type: Number,
    required: [true, 'Skill must have a percent!'],
    max: [100, 'percent must be below 100'],
    min: [0, 'percent must be above 0'],
  },
  name: {
    type: String,
    unique: true,
    trim: true,
    required: [true, 'Skill must have a name!'],
    maxlength: [30, 'A skill name must have less or equal then 20 characters'],
    minlength: [1, 'A skill name must have more or equal then 1 characters'],
  },
  originName: {
    type: String,
    select: false,
  },
  isDelete: {
    type: Boolean,
    select: false,
    default: false
  },
  createdAt: {
    type: Number,
    default: Date.now()
  },
  sort: {
    type: Number
  }
})

skillSchema.pre("save", function (next) {
  this.originName = this.name
  next();
});
skillSchema.post("save", function (doc, next) {
  // @ts-ignore 清除字段
  doc.isDelete = undefined
  doc.originName = undefined
  next();
});
skillSchema.pre(/^find/, function (next) {
  this.find({ isDelete: { $eq: false } })
  next();
});
skillSchema.pre("findOneAndUpdate", function (next) {
  // 非删除情况下的更新，需要更新 origin
  let updateContent: Record<string, any> = this.getUpdate() || {}
  if (!updateContent.isDelete) {
    // 添加更新值
    updateContent.name && this.set({ originName: updateContent.name })
  }
  // 删除情况
  else {
    this.set({ name: util.randomChars(15) })
  }
  next();
});
export default mongoose.model('Skill', skillSchema)
